/*
 * Created on Jun 14, 2005
 *
 */
package com.erclab.internal.xpresso.webapp.servlets;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.erclab.internal.xpresso.conf.Settings;
import com.erclab.internal.xpresso.exceptions.DirectoryException;
import com.erclab.internal.xpresso.security.User;

/**
 * @author Enrique Rodriguez.
 */
public class WebUserManagement {

	// Create the log for this class
	private static final Logger log = Logger.getLogger(WebUserManagement.class);
	

	public static User loadUser(HttpSession session, HttpServletRequest request) throws ServletException {
		User user = (User)session.getAttribute("user");
		if (user == null || user.getNetId().equals("")){
			try {
				log.info("User is null. load user");
				log.info("Remote user is: " + request.getRemoteUser());
				user = new User();
				user.setSessionId(session.getId());
				user.setNetId(request.getRemoteUser());
				user.setIpAddress(request.getRemoteAddr());
				Settings.getUserDirectory().loadUserBean(user);
				Settings.getUserDirectory().addVisitEntry(user);
				session.setAttribute("user", user);
				log.info("After loading the user");
			} catch (DirectoryException e2) {
				log.error("An DirectoryException occurred: " + e2);
				throw new ServletException(e2);
			}
			session.setAttribute("lang", Settings.getLanguageHandler().getLanguage(session));
		}
		return user;
	}

}
